<?php

class Jf_Event {

    public function getAllEvents () {
        $events = Jf_Config::factory ('xml', APPLICATION_PATH . '/configs/events.xml');
        return $events;
    }

    public function getEventListeners ($eventName) {
        $events = $this -> getAllEvents ();
        return $events[$eventName]['listeners'];
    }

    public function getEvents () {
        return array_keys ($this -> events);
    }

    public function _callMethod ($object, $method, $args) {
        if (method_exists ($object, $method)) {
            $object -> $method ($args);
        }
    }

    public function dispatch ($eventName, $eventArgs = null) {
        $listeners = $this -> getEventListeners ($eventName);
        $collection = new Jf_Event_Collection ($eventArgs);
        foreach ($listeners as $listener) {
            $object = Jf::loadModel ($listener['model']);
            self::_callMethod ($object, $listener['method'], $collection);
        }
    }

}
